package xj.graph2d.app.prop;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.swing.JMenuItem;

import xj.graph2d.DrawCanvas;
import xj.graph2d.DrawShape;
import xj.graph2d.GraphDocument;
import xj.graph2d.GraphEdgeBase;
import xj.graph2d.GraphNodeBase;
import xj.graph2d.SimpleDrawDocument;
import xj.graph2d.SimpleDrawView;
import xj.graph2d.app.DrawAction;

public class AlignHorizontalListener extends DrawAction implements ActionListener {

  public void actionPerformed(ActionEvent e) {
    if (e != null) {
      Object src = e.getSource();
      if (src != null && src instanceof JMenuItem) {
	JMenuItem b = (JMenuItem) src;
	String cmd = b.getActionCommand();

	if (main != null) {
	  SimpleDrawDocument doc = main.getDoc();
	  if (doc instanceof GraphDocument) {
	    GraphDocument graph = (GraphDocument) doc;
	    Set<DrawShape> sel = graph.getSelectionSet();
	    int n = sel.size();

	    // System.out.println("AlignHorizontalListener cmd=" +
	    // cmd + " n=" + n);

	    if (n == 0) {
	      DrawShape s = graph.getSelectedShape();
	      if (s instanceof GraphEdgeBase) {
		GraphDocument.Alignment align = GraphDocument.Alignment
		  .toAlignment(cmd);
		if (align == GraphDocument.Alignment.Center) {
		  align = GraphDocument.Alignment.CenterH;
		}
		graph.alignEdge((GraphEdgeBase) s, align);
	      }
	    } else if (n == 2) {
	      Iterator<DrawShape> iter = sel.iterator();
	      DrawShape s1 = iter.next();
	      DrawShape s2 = iter.next();
	      if (s1 instanceof GraphNodeBase && s2 instanceof GraphNodeBase) {
		GraphNodeBase node1 = (GraphNodeBase) s1;
		GraphNodeBase node2 = (GraphNodeBase) s2;
		graph.alignNodes(node1, node2, GraphDocument.Alignment
				 .toAlignment(cmd));
	      }
	    } else if (n > 2) {
	      Set<GraphNodeBase> nodes = new HashSet<GraphNodeBase>();
	      Iterator<DrawShape> iter = sel.iterator();
	      while (iter.hasNext()) {
		DrawShape s = iter.next();
		if (s instanceof GraphNodeBase) {
		  nodes.add((GraphNodeBase) s);
		}
	      }
	      graph.alignNodesHorizontal(nodes, GraphDocument.Alignment
					 .toAlignment(cmd));
	    }

	    SimpleDrawView view = main.getView();
	    DrawCanvas canvas = view.getCanvas();
	    canvas.repaint();
	  }
	}

      }
    }
  }

}